#include "MoistureMeterWatcher.h"
#include "ui_MoistureMeterWatcher.h"

MoistureMeterWatcher::MoistureMeterWatcher(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::MoistureMeterWatcher)
    , m_moisMeter(nullptr)
{
    ui->setupUi(this);
}

MoistureMeterWatcher::~MoistureMeterWatcher()
{
    delete ui;
}

/**
 * @brief 设置水分仪
 * @param moisMeter
 * @note moisMeter的管理权限交给MoistureMeterWatcher
 */
void MoistureMeterWatcher::setupMoistureMeter(GPAbstractMoistureMeter* moisMeter)
{
    m_moisMeter = moisMeter;
    if(m_moisMeter)
    {
        disconnect(m_moisMeter,&GPAbstractMoistureMeter::valueChange,this,&MoistureMeterWatcher::onValueChange);
    }
    if(moisMeter->parent() != this)
    {
        moisMeter->setParent(this);
    }
    connect(m_moisMeter,&GPAbstractMoistureMeter::valueChange,this,&MoistureMeterWatcher::onValueChange);
}

/**
 * @brief 水分仪的数值变化会触发此槽
 * @param index 品种序号
 * @param sample 品名代号P1~P24
 * @param temperature 温度【摄氏度】
 * @param weight 重量【g】
 * @param waterRatio 水分【%】
 * @param voltage 电压【V】
 * @param measureTimes 测量次数
 */
void MoistureMeterWatcher::onValueChange(int index, short sample, double temperature, double weight, double waterRatio, double voltage, int measureTimes)
{
    ui->labelIndex->setText(QString::number(index));
    ui->labelSample->setText(QString("P%1").arg(sample));
    ui->labelWaterRatio->setText(QString::number(waterRatio,'f',1));
    ui->labelTemp->setText(QString::number(temperature,'f',1));
    ui->labelWeight->setText(QString::number(weight,'f',0));
    if (measureTimes > 0)
    {
        ui->labelVoltage->setText(QString("%1 V | %2").arg(voltage,0,'f',1).arg(measureTimes));
    }
    else
    {
        ui->labelVoltage->setText(QString("%1 V").arg(voltage,0,'f',1));
    }
}

